package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"novel-mgmt/cache"
	"novel-mgmt/models"
	"strconv"
	"time"
)

func NovelList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var novels []models.Novel
	list_key := "list_key" + strconv.Itoa(page)
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Result()
	if cachejson == "" {
		models.DB.Offset(offset).Limit(size).Find(&novels)
		cachedata, _ := json.Marshal(&novels)
		cache.Rdb.Set(cache.Ctx, list_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &novels)
	}
	var total int64
	models.DB.Model(&models.Novel{}).Count(&total)
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  novels,
		"total": total,
	})
	return
}
func NovelDetail(c *gin.Context) {
	id := c.Query("id")
	detail_key := "detail_key" + id
	var novel models.Novel
	cachejson, _ := cache.Rdb.Get(cache.Ctx, detail_key).Result()
	if cachejson == "" {

		models.DB.Where("id=?", id).First(&novel)
		cachedata, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, detail_key, cachedata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &novel)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": novel,
	})
	return
}
